﻿using KingerRobot.MexicoSailunMDC.Dao;

namespace KingerRobot.MexicoSailunMDC.SpiService;

internal class BWcsWarehouseCrnMaterial : IWcsWarehouseCrnMaterial
{
    private readonly static IRcsEquipCrn _RcsEquipCrn = new BRcsEquipCrn();
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();

    public List<WarehouseCrnMaterialBean> GetWarehouseCrnMaterialByMaterialId(List<PORcsEquipCrn> crns, long MaterialId)
    {
        var db = Db.Default;
        // var crns = _RcsEquipCrn.GetRcsEquipCrn();
        var wcsWarehouseCrnMaterials = db.WcsWarehouseCrnMaterials.Where(t => t.UseFlag == 1 && t.MaterialId == MaterialId).Select(t => new
        {
            t.MaterialId,
            t.MaterialCount,
            t.CrnId,
        }).ToList();
        var result = crns.GroupJoin(wcsWarehouseCrnMaterials, f => f.Id, s => s.CrnId, (f, s) => new
        {
            Crns = f,
            CrnMaterial = s,
        }).SelectMany(t => t.CrnMaterial, (f, s) => new WarehouseCrnMaterialBean
        {
            MaterialId = s.MaterialId ?? 0,
            CrnId = f.Crns.Id ?? 0,
            WarehouseId = f.Crns.WarehourseId ?? 0,
            Count = s?.MaterialCount ?? 0,
        }).ToList();
        return result;
    }
    public int GetWareHouseStockNoSummaryByMaterialId(long materialId)
    {
        var crnMaterials = GetWcsWarehouseCrnMaterialsByMateiralId(materialId);
        var stock = crnMaterials.Sum(t => t.MaterialCount).GetValueOrDefault();

        // 未创建任务订单
        var count = _WmsOutOrderSummary.GetOutOrderSummaryNoTaskByMaterialId(materialId).Sum(t => t.PlanCount - t.RealCount) ?? 0;

        return stock - count;
    }

    public List<POWcsWarehouseCrnMaterial> GetWcsWarehouseCrnMaterialsByMateiralId(long mateiralId)
    {
        var db = Db.Default;
        var result = db.WcsWarehouseCrnMaterials.Where(t => t.MaterialId == mateiralId).ToList();
        return result;
    }
}

